package com.xpmusic.controller.admin;

import com.xpmusic.dao.impl.AdminDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@WebServlet("/deleteMusicServlet")
public class DeleteMusicServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String musicName = request.getParameter("musicName");
        System.out.println("musicName1:" + musicName);
        String path = this.getServletContext().getRealPath("/music/");

        //通过文件路径找到文件，然后删除文件
        File musicFile = new File(path + musicName.split("/")[2]);
        System.out.println("delete_path:" + path + musicName.split("/")[2]);
        boolean b_file = false;
        if(musicFile.exists()){
            b_file = musicFile.delete();
        }else{
            System.out.println("歌曲不存在");
        }
        musicName = musicName.split("-")[1].split(".mp3")[0];
        boolean b_sql = new AdminDaoImpl().deleteMusic(musicName);

        if(b_sql && b_file){
//            request.setAttribute("deleteSuccess","已经删除此歌曲！");
//            request.getRequestDispatcher("musicList.jsp").forward(request, response);
            request.getSession().setAttribute("deleteSuccess", "已经删除歌曲！");
            response.sendRedirect("musicList.jsp");
        }
//        if(b){
//            request.setAttribute("sql_success","文件资源不存在!已经删除此链接！");
//            request.getRequestDispatcher("musicList.jsp").forward(request, response);
//        }else {
//            response.sendRedirect("error.jsp");
//        }
    }
}
